package com.jdaw.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jdaw.reggie.common.R;
import com.jdaw.reggie.dto.DishDto;
import com.jdaw.reggie.entity.Category;
import com.jdaw.reggie.entity.Dish;
import com.jdaw.reggie.entity.DishFlavor;
import com.jdaw.reggie.entity.Employee;
import com.jdaw.reggie.service.CategoryService;
import com.jdaw.reggie.service.DishFlavorService;
import com.jdaw.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        //清理所有某个分类下的缓存
        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");
        return R.success("新增菜品成功");
    }

    /**
     * 分页
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        //分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.like(name!=null,Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo,queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPageInfo,"records");
        List<Dish> records = pageInfo.getRecords();
        //为page的每一个dto都赋值
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPageInfo.setRecords(list);
        return R.success(dishDtoPageInfo);
    }

    /**
     * 获取菜品信息
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto dishDto=dishService.getByIdWithFlavor(id);
        if(dishDto!=null){
            return R.success(dishDto);
        }
        return R.error("该菜品无法找到");
    }

    /**
     * 更新菜品
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);

        //清理所有某个分类下的缓存
        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");

        return R.success("修改菜品成功");
    }


    /**
     * 根据分类查询菜品以及口味信息
     */
    @GetMapping("/list")
    public R<List<DishDto>> listDto(Dish dish){
        List<DishDto> listDto=null;
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        listDto=(List<DishDto>)redisTemplate.opsForValue().get(key);
        if(listDto!=null){
            return R.success(listDto);
        }

        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<Dish>();
        //选择status等于1的，表示未停售
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.orderByAsc(Dish::getSort);

        List<Dish> list = dishService.list(queryWrapper);
        listDto = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //获取菜品口味
            Long dishId=item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        //如果没有在redis中找到就查数据库放入redis
        redisTemplate.opsForValue().set(key,listDto,60, TimeUnit.MINUTES);
        return R.success(listDto);
    }

    /**
     * 删除菜品
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        dishService.removeWithFlavor(ids);
        return R.success("删除成功");
    }

    /**
     * 停售菜品
     */
    @PostMapping("/status/0")
    public R<String> stopSell(@RequestParam List<Long> ids){
        log.info(ids.toString());
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId,ids);
        List<Dish> list=dishService.list(queryWrapper);
        for (Dish dish:list) {
            dish.setStatus(0);
            dishService.updateById(dish);
        }
        return R.success("商品已停售");
    }

    /**
     * 起售菜品
     */
    @PostMapping("/status/1")
    public R<String> startSell(@RequestParam List<Long> ids){
        log.info(ids.toString());
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId,ids);
        List<Dish> list=dishService.list(queryWrapper);
        for (Dish dish:list) {
            dish.setStatus(1);
            dishService.updateById(dish);
        }
        return R.success("商品已起售");
    }

}
